﻿using UnityEngine;
using System.Collections;
using System.Reflection;

/// <summary>
/// This attribute is used to represent a string value
/// for a value in an enum.
/// </summary>
public class StringValueAttribute : System.Attribute
{
	#region Properties

	/// <summary>
	/// Holds the stringvalue for a value in an enum.
	/// </summary>
	public string StringValue { get; protected set; }

	#endregion

	#region Constructor

	/// <summary>
	/// Constructor used to init a StringValue Attribute
	/// </summary>
	/// <param name="value"></param>
	public StringValueAttribute(string value)
	{
		this.StringValue = value;
	}

	#endregion
}

/// <summary>
/// Enum extensions.
/// </summary>
public static class EnumExtensions
{
	/// <summary>
	/// Will get the string value for a given enums value, this will
	/// only work if you assign the StringValue attribute to
	/// the items in your enum.
	/// </summary>
	/// <param name="value"></param>
	/// <returns></returns>
	public static string GetStringValue(this System.Enum value)
	{
		// Get the type
		System.Type type = value.GetType();

		// Get fieldinfo for this type
		FieldInfo fieldInfo = type.GetField(value.ToString());

		// Get the stringvalue attributes
		StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];

		// Return the first if there was a match.
		return attribs.Length > 0 ? attribs[0].StringValue : null;
	}
}

/// <summary>
/// Enum Utility
/// </summary>
public static class wsEnum
{
	/// <summary>
	/// Get random value from enum values.
	/// </summary>
	/// <typeparam name="T"></typeparam>
	/// <returns></returns>
	public static T RandomEnum<T>()
	{
		T[] values = (T[])System.Enum.GetValues(typeof(T));
		return values[new System.Random().Next(0, values.Length)];
	}

	/// <summary>
	/// convert enum values to list.
	/// </summary>
	/// <typeparam name="T"></typeparam>
	/// <returns></returns>
	public static T[] GetEnumArray<T>()
	{
		return (T[])System.Enum.GetValues(typeof(T));
	}
}
